package cn.concurrence.readwrite;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author summit
 * @since 2022/4/24 14:17
 */
public class ReadWriteTest {


	public static void main(String[] args) {
		Cache cache = new Cache();

		for (int i = 0; i < 5; i++) {
			int finalI = i;
			new Thread(() -> {
				cache.put("thread" + finalI, "value");
			}, String.valueOf(i)).start();
		}

		for (int i = 0; i < 5; i++) {
			int finalI = i;
			new Thread(() -> {
				cache.get("thread" + finalI);
			}, String.valueOf(i)).start();
		}
	}
}

class Cache {

	private ReentrantReadWriteLock rw = new ReentrantReadWriteLock();

	private Map<String, String> map = new ConcurrentHashMap<>();

	public void put(String key, String value) {
		rw.writeLock().lock();

		try {
			System.out.println("正在设值=======");
			map.put(key, value);

			TimeUnit.SECONDS.sleep(1);
			System.out.println("设值结束=======");

		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			rw.writeLock().unlock();

		}

	}

	public void get(String key) {
		rw.readLock().lock();

		try {
			System.out.println("正在获取=======");
			map.get(key);
			TimeUnit.SECONDS.sleep(1);

			System.out.println("获取结束=======");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			rw.readLock().unlock();
		}

	}
}
